<template>
	<div class="login-container" :style="{ background: `url(${backgroundImage}) no-repeat` }">
		<div class="login-icon-group">
			<div class="login-icon-group-title">
				<img src="/favicon.png" />
				<div class="login-icon-group-title-text font25">{{ getThemeConfig.globalViceTitle }}</div>
			</div>
		</div>
		<div class="login-content">
			<div class="login-content-main">
				<h4 class="login-content-title">{{ getThemeConfig.globalTitle }}</h4>
				<div class="login-content-main-sacn" @click="isScan = !isScan">
					<i class="iconfont" :class="isScan ? 'icon-diannao1' : 'icon-barcode-qr'"></i>
					<div class="login-content-main-sacn-delta"></div>
				</div>
				<Scan v-if="isScan && loginConfig.scanEnable" :model="loginConfig.scanModes" />
				<div v-else>
					<el-tabs v-model="tabsActiveName">
						<el-tab-pane v-if="loginConfig.accountEnable" :label="$t('message.label.account')" name="account">
							<Account v-if="!loginConfig.dynamicEnable" :tenantEnable="loginConfig.tenantEnable" @success="onSignInSuccess"/>
							<Account2 v-else :tenantEnable="loginConfig.tenantEnable" @success="onSignInSuccess"/>
						</el-tab-pane>
						<el-tab-pane v-if="loginConfig.mobileEnable || loginConfig.emailEnable" :label="$t('message.label.mobile')" name="mobile">
							<Mobile @success="onSignInSuccess"/>
						</el-tab-pane>
					</el-tabs>
				</div>
			</div>
		</div>
		<div class="login-copyright">
			<div class="mb5 login-copyright-company">{{ $t('message.copyright.company') }}</div>
			<a class="login-copyright-msg" href="https://beian.miit.gov.cn/" target="_blank" :underline="false">
				{{ $t('message.copyright.recordno') }}
			</a>
		</div>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, computed, defineComponent, onBeforeMount, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useThemeConfig } from '/@/stores/themeConfig';
import { NextLoading } from '/@/utils/loading';
import { Session } from '/@/utils/storage';
import { useI18n } from 'vue-i18n';
import { formatAxis } from '/@/utils/formatTime';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import Account from '/@/views/login/component/account.vue';
import Account2 from '/@/views/login/component/account2.vue';
import Mobile from '/@/views/login/component/mobile.vue';
import Scan from '/@/views/login/component/scan.vue';
import { getConfigLogin, scanLogin, getLoginUserInfo, getLoginUserAuthPage, getLoginUserAuthBtn } from '/@/api/login/index';

// 定义接口来定义对象的类型
interface LoginState {
	tabsActiveName: string;
	isScan: boolean,
	loginConfig: {
		tenantEnable: boolean;
		accountEnable: boolean;
		dynamicEnable: boolean;
		mobileEnable: boolean;
		emailEnable: boolean;
		scanEnable: boolean;
		scanModes: Array<string>;
	}
}

export default defineComponent({
	name: 'login',
	components: { Account, Account2, Mobile, Scan },
	setup() {
		const publicUrl = import.meta.env.VITE_PUBLIC_PATH as string;
		const serverUrl = import.meta.env.VITE_SERVER_URL as string;
		const { t } = useI18n();
		const route = useRoute();
		const router = useRouter();
		const storesThemeConfig = useThemeConfig();
		const { themeConfig } = storeToRefs(storesThemeConfig);
		const backgroundImage = `${serverUrl}/api-system/bing/image/preview/today`;
		const state = reactive<LoginState>({
			tabsActiveName: 'account',
			isScan: false,
			loginConfig: {
				tenantEnable: false,
				accountEnable: true,
				dynamicEnable: false,
				mobileEnable: false,
				emailEnable: false,
				scanEnable: false,
				scanModes: [],
			}
		});
		// 获取布局配置信息
		const getThemeConfig = computed(() => {
			return themeConfig.value;
		});
		
		const getUrlParam = (key: string) => {
			const reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
			const r = window.location.search.substring(1).match(reg);
			if (r != null) return r[2]; return null;
		}
		
		// Oauth授权码登录
		const signInByOauthCode = () => {
			const code = getUrlParam('code');
			const state = getUrlParam('state');
			const token = Session.get('token');
			if(code && state && !token){
				scanLogin({code: code, state: state}).then(async (res: any) => {
					if(res.code === 0){
						Session.set('token', res.data.accessToken);
						Session.set('refreshToken', res.data.refreshToken);
						await initLoginUserInfo();
						await initBackEndControlRoutes();
						//曲线救国方式进行跳转
						if(route.query?.redirect){
							window.location.href= window.location.origin + window.location.pathname + "#" + route.query?.redirect;
						}else{
							window.location.href= window.location.origin + window.location.pathname + "#/";
						}
					}
				});
			}
		}
		
		const onSignInSuccess = async () => {
			await initLoginUserInfo();
			await initBackEndControlRoutes();
			await successRouterForward();
		}
		
		// 加载存储用户信息
		const initLoginUserInfo = async () => {
			const info = await getLoginUserInfo() as any;
			const page = await getLoginUserAuthPage() as any;
			const butn = await getLoginUserAuthBtn() as any;
			
			const userInfo = info.code == 0 ? info.data : {};
			userInfo.avatar = userInfo.avatar ? userInfo.avatar : publicUrl + 'images/login/profile.png';
			userInfo.authPageList = page.code == 0 ? page.data : [];
			userInfo.authBtnList = butn.code == 0? butn.data : [];
			
			// 存储用户信息到浏览器缓存
			Session.set('userInfo', userInfo);
		}
		
		// 登录成功后的跳转
		const successRouterForward = async () => {
			// 登录成功，跳到转首页
			if (route.query?.redirect) {
				const query = Object.keys(route.query?.params as object).length > 0 ? JSON.parse(route.query?.params as string) : '';
				router.push({
					path: route.query?.redirect as string,
					query: query,
				});
			} else {
				router.push('/');
			}
			// 初始化登录成功时间问候语
			let currentTimeInfo = formatAxis(new Date());
			// 登录成功提示
			const signInText = t('message.signInText');
			ElMessage.success(`${currentTimeInfo}，${signInText}`);
			// 添加 loading，防止第一次进入界面时出现短暂空白
			NextLoading.start();
		};
		
		// 设置初始化
		onBeforeMount(() => {
			// Oauth授权码登录
			signInByOauthCode();
		});
		
		// 页面加载时
		onMounted(async () => {
			Session.clear();
			await getConfigLogin().then((res: any) => {
				if(res.code == 0){
					state.loginConfig = res.data;
					if(res.data.accountEnable){
						state.tabsActiveName = 'account';
					}else if(res.data.dynamicEnable){
						state.tabsActiveName = 'account';
					}else{
						state.tabsActiveName = 'mobile';
					}
				}
			})
			NextLoading.done();
		});
		return {
			getThemeConfig,
			backgroundImage,
			onSignInSuccess,
			...toRefs(state),
		};
	},
});
</script>

<style scoped lang="scss">
.login-container {
	width: 100%;
	height: 100%;
	position: relative;
	// background-image: url('https://bing.img.run/rand_uhd.php') no-repeat;
	background-size: 100% 100%;
	.login-icon-group {
		width: 100%;
		height: 100%;
		position: relative;
		.login-icon-group-title {
			position: absolute;
			top: 50px;
			left: 80px;
			display: flex;
			align-items: center;
			img {
				width: 30px;
				height: 30px;
			}
			&-text {
				padding-left: 15px;
				color: var(--el-color-primary);
			}
		}
	}
	.login-content {
		width: 500px;
		padding: 20px;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%) translate3d(0, 0, 0);
		background-color: var(--el-color-white);
		border: 5px solid var(--el-color-primary-light-8);
		border-radius: 4px;
		transition: height 0.2s linear;
		min-height: 400px;
		overflow: hidden;
		z-index: 1;
		.login-content-main {
			margin: 0 auto;
			width: 80%;
			.login-content-title {
				color: var(--el-text-color-primary);
				font-weight: 500;
				font-size: 22px;
				text-align: center;
				letter-spacing: 4px;
				margin: 5px 0 10px;
				white-space: nowrap;
				z-index: 5;
				position: relative;
				transition: all 0.3s ease;
			}
		}
		.login-content-main-sacn {
			position: absolute;
			top: 0;
			right: 0;
			width: 50px;
			height: 50px;
			overflow: hidden;
			cursor: pointer;
			transition: all ease 0.3s;
			color: var(--el-text-color-primary);
			&-delta {
				position: absolute;
				width: 35px;
				height: 70px;
				z-index: 2;
				top: 2px;
				right: 21px;
				background: var(--el-color-white);
				transform: rotate(-45deg);
			}
			&:hover {
				opacity: 1;
				transition: all ease 0.3s;
				color: var(--el-color-primary) !important;
			}
			i {
				width: 47px;
				height: 50px;
				display: inline-block;
				font-size: 48px;
				position: absolute;
				right: 2px;
				top: -1px;
			}
		}
	}
	
	.login-copyright {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 30px;
		text-align: center;
		color: var(--el-color-white);
		font-size: 12px;
		opacity: 0.8;
		.login-copyright-company {
			white-space: nowrap;
		}
		.login-copyright-msg {
			color: var(--el-color-white);
			text-decoration: none;
			@extend .login-copyright-company;
		}
	}
}
</style>
